package com.quectel.core.config;

import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.JdbcTransactionManager;

import javax.sql.DataSource;

/**
 * 事务管理器
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2023-04-26 14:01:00
 */
@Configuration
public class TransactionManagerConfig {

    public static final String MONGO_TRANSACTION_MANAGER = "mongoTransactionManager";

    /**
     * 其他事务管理器会覆盖默认的事务管理器 所以需要重新设置并指定为默认事物管理器
     *
     * @param dataSource
     * @return
     * @see DataSourceTransactionManagerAutoConfiguration
     */
    @Bean
    @Primary
    public DataSourceTransactionManager defaultTransactionManager(Environment environment, DataSource dataSource) {
        return environment.getProperty("spring.dao.exceptiontranslation.enabled", Boolean.class, Boolean.TRUE)
                ? new JdbcTransactionManager(dataSource) : new DataSourceTransactionManager(dataSource);
    }

    /**
     * mongodb事务管理器
     *
     * @param factory
     * @return
     */
    @Bean(name = MONGO_TRANSACTION_MANAGER)
    public MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory factory) {
        return new MongoTransactionManager(factory);
    }
}
